package com.mocoop.jfqc;

import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout.LayoutParams;
import cn.jpush.android.api.JPushInterface;

import com.mocoop.activity.MocoopActivity;
import com.mocoop.activity.MocoopTabHost.MocoopTabHostListener;
import com.mocoop.entity.PageInfoEntity;
import com.mocoop.plugin.page.pagesService;

public class JFQCActivity {
	public static final String MESSAGE_RECEIVED_ACTION = "com.mocoop.jfgf.MESSAGE_RECEIVED_ACTION";
	public static final String MESSAGE_ALERT = "alertMsg";
	public static final String START_ACTIVITY_FOR_RESULT = "startActivityForResult";
	
	private static boolean isInbackgroud;
	private MessageReceiver mMessageReceiver;
	private MocoopActivity mocoopActivity;
	private MocoopTabHostListener mocoopTabHostListener;

	private ImageView launchView;

	public JFQCActivity(Activity mocoopActivity) {
		super();
		this.mocoopActivity = (MocoopActivity) mocoopActivity;
		this.mocoopTabHostListener = (MocoopTabHostListener) mocoopActivity;
		onCreate();
	}

	public static boolean isInbackgroud() {
		return isInbackgroud;
	}

	public static void setInbackgroud(boolean isInbackgroud) {
		JFQCActivity.isInbackgroud = isInbackgroud;
	}

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		mocoopActivity.registerReceiver(mMessageReceiver, filter);
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, final Intent intent) {
			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
				if (intent.getBooleanExtra(MESSAGE_ALERT, false)) {
					Bundle bundle = intent.getExtras();
					AlertDialog.Builder builder = new AlertDialog.Builder(context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

					builder.setTitle("新消息");
					builder.setMessage(bundle.getString(JPushInterface.EXTRA_MESSAGE));
					builder.setNeutralButton("查看", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							String extras = intent.getStringExtra(JPushInterface.EXTRA_EXTRA);
							if (!TextUtils.isEmpty(extras)) {
								jumpToApprovalInfo(extras);
							}
							dialog.dismiss();
						}
					});
					builder.setNegativeButton("忽略", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							dialog.dismiss();

						}
					});
					builder.create().show();

				} else {
					String extras = intent.getStringExtra(JPushInterface.EXTRA_EXTRA);
					if (!TextUtils.isEmpty(extras)) {
						jumpToApprovalInfo(extras);
					}
				}
			}
		}
	}

	public void jumpToApprovalInfo(String extras) {
		StringBuilder url = new StringBuilder();
		PageInfoEntity pageInfo = new PageInfoEntity();
		pageInfo.setAnimated(true);
		try {
			JSONObject jsonObject = new JSONObject(extras);// {"type":"approval","idx":3,"taskID":"purorder.BG0000000000008300xx"}
			
			url.append(jsonObject.getString("url"));
			pageInfo.setTitle(jsonObject.getString("title"));
			pageInfo.setConfigFileSubPath(jsonObject.getString("style"));
			
			JSONObject params = jsonObject.getJSONObject("params");
			url.append("?");
			Iterator<String> it = params.keys();
			while (it.hasNext()) {
				String key = it.next();
				url.append(key);
				url.append("=");
				url.append(jsonObject.get(key));
				url.append("&");
			}
			url.append("userID=");
			SharedPreferences sharedPreferences = mocoopActivity.getSharedPreferences(MocoopActivity.MOCOOP_CONFIG, 0);
			url.append(sharedPreferences.getString(MocoopActivity.USER_ID, ""));
		} catch (JSONException e) {
			e.printStackTrace();
		}

		
		pageInfo.setUrl(url.toString());
		mocoopActivity.jumpNewPage(pageInfo);
	}

	public void onCreate() {
		
	}

	public void onDestroy() {
		mocoopActivity.unregisterReceiver(mMessageReceiver);
	}

	protected void onStart() {
		isInbackgroud = false;
	}

	protected void onStop() {
		isInbackgroud = true;
	}

	public PageInfoEntity changeItemListener(int id) {
		mocoopActivity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				mocoopActivity.getCurrentView().showTitleStatus();
			}
		});
		PageInfoEntity pageInfo = new PageInfoEntity();
		switch (id) {
		case R.id.itemOne:
			pageInfo.setTitle(mocoopActivity.getResources().getString(R.string.itemOne));
			pageInfo.setUrl("abnormal.html");
			break;
		case R.id.itemTwo:
			pageInfo.setTitle(mocoopActivity.getResources().getString(R.string.itemTwo));
			pageInfo.setConfigFileSubPath("config/theme-orders.json");
			pageInfo.setMocoopStyle(pagesService.getStyleObject(pageInfo.getConfigFileSubPath(), mocoopActivity));
			pageInfo.setUrl("orders.html");
			break;
		case R.id.itemThree:
			pageInfo.setTitle(mocoopActivity.getResources().getString(R.string.itemThree));
			pageInfo.setUrl("dynamic.html");
			break;
		case R.id.itemFour:
			pageInfo.setTitle(mocoopActivity.getResources().getString(R.string.itemFour));
			pageInfo.setUrl("self.html");
			break;
		default:
			break;
		}
		return pageInfo;
	}

	public PageInfoEntity getLaunchPage() {
		PageInfoEntity pageInfo = new PageInfoEntity();
		pageInfo.setTitle(mocoopActivity.getResources().getString(R.string.itemOne));
		pageInfo.setUrl("abnormal.html");
		return pageInfo;
	}

	public void showLaunchView() {
		launchView = new ImageView(mocoopActivity);
		launchView.setBackgroundColor(android.graphics.Color.parseColor("#ffffff"));
		launchView.setImageResource(R.drawable.logo_loading);
		launchView.setScaleType(ScaleType.CENTER);
		launchView.setClickable(true);
		LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		mocoopActivity.addContentView(launchView, layoutParams);

//		launchView.setOnClickListener(new View.OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				((ViewGroup) launchView.getParent()).removeView(launchView);
//			}
//		});
	}

	public void hideLauchView() {
		mocoopActivity.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				((ViewGroup) launchView.getParent()).removeView(launchView);
			}
		});
		
	}

	public void messageCountController(final String tabName, final String msg) {
		mocoopActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if ("abnormal".equals(tabName)) {
					mocoopTabHostListener.getMocoopTabHost().itemOne.setCountMsg(msg);
				} else if ("remark".equals(tabName)) {
					mocoopTabHostListener.getMocoopTabHost().itemThree.setCountMsg(msg);
				} else if ("order".equals(tabName)) {
					mocoopTabHostListener.getMocoopTabHost().itemTwo.setCountMsg(msg);
				} else if ("me".equals(tabName)) {
					mocoopTabHostListener.getMocoopTabHost().itemFour.setCountMsg(msg);
				}
			}
		});
	}

	public interface BaseActivity{
		public JFQCActivity getJFQCActivity();
	}
}
